package org.jlamp.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.util.concurrent.DefaultThreadFactory;
import org.jlamp.core.util.JlampUtils;

import java.io.PrintStream;

/**
 * Jlamp服务端
 *
 * @author zhangcs
 */
public class JlampServer {

    private final PrintStream logger;

    /**
     * 绑定端口
     */
    private int port;

    /**
     * 监听连接线程
     */
    private final EventLoopGroup bossGroup = new NioEventLoopGroup(1, new DefaultThreadFactory("jlamp-server-boss", true));

    /**
     * 工作线程
     */
    private final EventLoopGroup workerGroup = new NioEventLoopGroup(new DefaultThreadFactory("jlamp-server-worker", true));

    private Channel channel;

    public JlampServer() {
        this.logger = JlampUtils.logger();
    }

    public void start(int port) throws Exception {
        this.port = port;
        start();
    }

    /**
     * 启动服务
     *
     * @throws Exception 服务中断时抛出此异常
     */
    public void start() throws Exception {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(bossGroup, workerGroup)
                // NIO 模式
                .channel(NioServerSocketChannel.class)
                .childHandler(new JlampSocketServerInitializer())
                .childOption(ChannelOption.SO_KEEPALIVE, true);

        String host = "localhost";
        channel = bootstrap.bind(host, port).sync().channel();
        logger.println("JLamp server listen at " + host + ":" + port);
    }

    /**
     * 停止服务
     */
    public void stop() {
        if (channel != null) {
            channel.close();
        }
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }

}
